<template>
  <div class="searchSuggestion">
    <van-cell
      icon="search"
      v-for="(suggestion, i) in suggestions"
      :key="i"
      @click="search(suggestion)"
    >
      <div slot="title" v-html="hightLight(suggestion)"></div>
    </van-cell>
  </div>
</template>

<script>
// 导入api
import { getSearchSuggestion } from '@/api/search'
// 导入防抖动函数
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    // 关键词
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  created() {},
  mounted() {},
  activited() {},
  update() {},
  beforeRouteUpdate() {},
  methods: {
    // 根据关键词设置联想建议高亮
    hightLight(suggestion) {
      // 根据关键词创建替换的正则
      // 正则实例可以根据变量创建正则
      const reg = new RegExp(this.searchText, 'gi')
      // 高亮文本
      const hightLightStr = `<span style="color:#3296fa">${this.searchText}</span>`
      return suggestion.replace(reg, hightLightStr)
    },
    search(suggestion) {
      this.$emit('getRes', suggestion)
    }
  },
  filter: {},
  computed: {},
  watch: {
    // 监听搜索关键词searchText
    searchText: {
      // 监听的回调

      // debounce 返回防抖动的函数
      handler: debounce(async function(NewValue) {
        // 关键词变化,自动发起axios请求,拿到新的联想建议
        try {
          // console.log(NewValue)
          const { data } = await getSearchSuggestion(NewValue)
          // console.log(data)
          // 拿到联想建议的数组,并绑定到模板
          this.suggestions = data.data.options
        } catch (error) {
          this.$toast.fail('获取联想失败')
        }
      }, 250),
      // 模板渲染立即调用
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped></style>
